<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Stocks extends CI_Controller
{

    /**
     * 库存列表
     *
     * Maps to the following URL
     *        http://example.com/index.php/welcome
     *    - or -
     *        http://example.com/index.php/welcome/index
     *    - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    function __construct()
    {
        parent::__construct();
        $this->load->model('Function_m','fun');
        $this->pageSize =$this->config->item('pagenum');
    }
	
	/**
	  +----------------------------------------------------------
	 * 工厂的物料入库管理
	  +----------------------------------------------------------
	 * @return array
	 * 2017 07 11  liu
	  +----------------------------------------------------------
	 */
	public function Material()
	{
		
        $this ->tpl->display("stocks/material.tpl");
	}
    //退货列表
    public function returnGoodsList(){
        $where = " ";
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        //商品编号
        $goods_sku =  trim($this->input->get('goods_sku'));
        if($goods_sku){
            $where.= " AND a.sku = '{$goods_sku}' ";
            $this->tpl->assign("goods_sku", $goods_sku);
        }
        $goods_name =  trim($this->input->get('goods_name'));
        if($goods_name){
            $where.= " AND a.skuname = '{$goods_name}' ";
            $this->tpl->assign("goods_name", $goods_name);
        }
        $mborder = trim($this->input->get('mborder'));
        if($mborder){
            $where.=" AND a.mborderid = '{$mborder}' ";
            $this->tpl->assign('mborder',$mborder);
        }
        $fmorder = trim($this->input->get('fmorder'));
        if($fmorder){
            $where.=" AND a.fmorderid = '{$fmorder}' ";
            $this->tpl->assign('fmorder',$fmorder);
        }
        $property = trim($this->input->get('property'));
        if($property){
            $where.=" AND a.property = '{$property}' ";
            $this->tpl->assign('property',$property);
        }
      

		 //工厂
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$where.=" AND a.factory = 1 ";
		}
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$where.=" AND a.factory = 2 ";
		}
		if($_COOKIE["department"] ==1)	//工厂2人员
		{
			  $factory = trim($this->input->get('factory'));
			if($factory){
				if($factory==1){
					$where.="  AND (a.factory = '{$factory}' or a.factory= 12) ";
				}
				if($factory==2){
					$where.="  AND (a.factory = '{$factory}' or a.factory= 10) ";
				}
				$this->tpl->assign('factory',$factory);
			}
		}



        $starttime = trim($this->input->get('starttime'));
        if($starttime){
            $this->tpl->assign("starttime", $starttime);
            $where .= " AND a.opertime >= '$starttime' ";
        }
        $endtime = trim($this->input->get('endtime'));
        if($endtime){
            $this->tpl->assign("endtime", $endtime);
            $endtime = $endtime." 23:59:59";
            $where .= " AND a.opertime <= '$endtime' ";
        }
        $flag = trim($this->input->get('flag'));
        if($flag){
            $where.=" AND a.flag = '{$flag}' ";
            $this->tpl->assign('flag',$flag);
        }

        $where .= "AND a.flag != 4 ";
        $join = "LEFT JOIN d_producttype b ON a.producttype = b.id ";
        $join.= "LEFT JOIN d_user c ON a.createoper = c.id ";
        $where .= " GROUP BY a.id ";
        $orderby = " order by a.id DESC";
        $fields = " a.*,b.measure,b.type,b.age,c.name as createoper,c.name as oper ";

        $flag_excel = $this->input->get("flag_excel");
        if($flag_excel == 1){
            require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
            $objExcel = new PHPExcel();
            $this->pageSize = 1000000;
            $list = $this->fun->getalllist('d_outproduct a', $where, $nowpage, $if_csv, $this->pageSize, $orderby,$fields,$join);

            //自定义 长 宽
            $objExcel->setActiveSheetIndex(0);
            $objExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight();
            $objExcel->getActiveSheet()->getColumnDimension('A')->setWidth();
            $objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(50);
            $objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
            $objExcel->getActiveSheet()->getColumnDimension('D')->setWidth();
            $objExcel->getActiveSheet()->getColumnDimension('E')->setWidth();
            $objExcel->getActiveSheet()->getColumnDimension('F')->setWidth();
            $objExcel->getActiveSheet()->getColumnDimension('G')->setWidth();
            $objExcel->getActiveSheet()->getColumnDimension('H')->setWidth();
            $objExcel->getActiveSheet()->getColumnDimension('I')->setWidth();
            $objExcel->getActiveSheet()->getColumnDimension('J')->setWidth();
            $objExcel->getActiveSheet()->getColumnDimension('K')->setWidth(20);
            $objExcel->getActiveSheet()->getColumnDimension('L')->setWidth();


            //设置标题
            $objExcel->setActiveSheetIndex(0)->setCellValue('A1','商品SKU');
            $objExcel->setActiveSheetIndex(0)->setCellValue('B1','商品名称');
            $objExcel->setActiveSheetIndex(0)->setCellValue('C1','商品型号');
            $objExcel->setActiveSheetIndex(0)->setCellValue('D1','退货状态');
            $objExcel->setActiveSheetIndex(0)->setCellValue('E1','工厂订单');
            $objExcel->setActiveSheetIndex(0)->setCellValue('F1','数量');
            $objExcel->setActiveSheetIndex(0)->setCellValue('G1','单价');
            $objExcel->setActiveSheetIndex(0)->setCellValue('H1','工厂');
            $objExcel->setActiveSheetIndex(0)->setCellValue('I1','属性标注');
            $objExcel->setActiveSheetIndex(0)->setCellValue('J1','创建人');
            $objExcel->setActiveSheetIndex(0)->setCellValue('K1','创建时间');
            $objExcel->setActiveSheetIndex(0)->setCellValue('L1','描述');
            foreach($list['list'] as $k=>$v){

                $sql = "SELECT * FROM db_goods WHERE goods_sku = '{$v['sku']}' and goods_parent_sku = '{$v['sku']}'  ";
                $rs = $this->db->query($sql)->row_array();
                if($rs){
                   // if(strlen($v['fmorderid'])>=6){
                        $v['price'] = $rs['g_costprice'];
                  //  }else{
                   //     $v['price'] = $rs['bulkprice'];
                   // }
                }

                $count = $k+2;
                $objExcel->setActiveSheetIndex(0)->setCellValue('A'.$count,$v['sku']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('B'.$count,$v['skuname']);
                if($v['measure']){
                    $type = $v['measure'].",".$v['type'].",".$v['age'];
                    $objExcel->setActiveSheetIndex(0)->setCellValue('C'.$count,$type);
                }else{
                    $objExcel->setActiveSheetIndex(0)->setCellValue('C'.$count,"");
                }
                if($v['flag']==1){
                    $msg = "新退货";
                }
                if($v['flag']==2){
                    $msg = "正常入库";
                }
                if($v['flag']==3){
                    $msg = "其他处理";
                }
                if($v['flag']==4){
                    $msg = "作废";
                }
                if($v['flag']==4){
                    $msg = "损坏商品";
                }

                $objExcel->setActiveSheetIndex(0)->setCellValue('D'.$count,$msg);
                $objExcel->setActiveSheetIndex(0)->setCellValue('E'.$count,$v['fmorderid']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('F'.$count,$v['ordernum']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('G'.$count,$v['price']);
                if($v['factory']==12 || $v['factory']==1){
                    $message = "工厂1";
                }
                if($v['factory']==10 || $v['factory']==2){
                    $message = "工厂2";
                }

                $objExcel->setActiveSheetIndex(0)->setCellValue('H'.$count,$message);

                $objExcel->setActiveSheetIndex(0)->setCellValue('I'.$count,$v['property']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('J'.$count,$v['createoper']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('K'.$count,$v['opertime']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('L'.$count,$v['descr']);
            }
            $excel_name = date("YmdHis");
            header("Content-type:application/vnd.ms-excel;charset=gb2312");
            header('Content-Disposition: attachment;filename="'.$excel_name.'.xls"');
            header('Cache-Control: max-age=0');
            $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
            $objWriter->save('php://output');
            exit;



        }



        $list = $this->fun->getalllist('d_outproduct a', $where, $nowpage, $if_csv, $this->pageSize, $orderby,$fields,$join);
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        foreach($list['list'] as $k=>$v){
            $sql = "SELECT * FROM db_goods WHERE goods_sku = '{$v['sku']}' and goods_parent_sku = '{$v['sku']}'  ";
            $rs = $this->db->query($sql)->row_array();
            if($rs){
                  // if(strlen($v['fmorderid'])>=6){
                       $list['list'][$k]['price'] = $rs['g_costprice'];
                  // }else{
                   //    $list['list'][$k]['price'] = $rs['bulkprice'];
                //   }
            }

        }
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("stocklist", $list["list"]);
        $this ->tpl->display("stocks/returngoodslist.tpl");

    }
    public function addReturnGoods(){
        if($this->input->post()){
            //添加退货商品
            $arr_goods["sku"] = trim($this->input->post("goods_sku"));
            $arr_goods["skuname"] = trim($this->input->post("goods_name"));
            $arr_goods["ordernum"] = trim($this->input->post("ordernum"));
            if(trim($this->input->post("producttype"))){
                $arr_goods["producttype"]=trim($this->input->post("producttype"));
            }
            $arr_goods["factory"] = trim($this->input->post("factory"));
            /**
            if(trim($this->input->post("mborder"))){
                $arr_goods["mborderid"] = trim($this->input->post("mborder"));
            }**/
            if(trim($this->input->post("fmorder"))){
                $arr_goods["fmorderid"] = trim($this->input->post("fmorder"));
            }
            if(trim($this->input->post("property"))){
                $arr_goods["property"] = trim($this->input->post("property"));
            }
            if(trim($this->input->post("descr"))){
                $arr_goods["descr"] = trim($this->input->post("descr"));
            }
            $arr_goods["createoper"] = $_COOKIE['userid'];
            $arr_goods['oper'] = $_COOKIE['userid'];
            $arr_goods['opertime'] = date("Y-m-d H:i:s");
            // flag 1 新退货
            $arr_goods['flag'] = 1;

            $this->db->insert("d_outproduct",$arr_goods);
            $insert_id = $this->db->insert_id();
            if($insert_id){
                $arr = array('code'=>200,"msg"=>"添加退货商品成功!");
            }else{
                $arr = array('code'=>0,"msg"=>"添加退货商品失败!");
            }
            echo json_encode($arr);exit;

        }else{
            $sql = "SELECT * FROM d_producttype ";    //获取商品型号
            $lists= $this->db->query($sql)->result_array();
            $this->tpl->assign('lists',$lists);
            $this->tpl->display("stocks/addreturngoods.tpl");
        }
    }
    public function editReturnGoods(){
        if($this->input->post()){
            //添加退货商品
            //$arr_goods["sku"] = trim($this->input->post("goods_sku"));
            //$arr_goods["skuname"] = trim($this->input->post("goods_name"));
            $arr_goods["ordernum"] = trim($this->input->post("ordernum"));
            $arr_goods["producttype"]=trim($this->input->post("producttype"));
            $arr_goods["factory"] = trim($this->input->post("factory"));
            if(trim($this->input->post("mborder"))){
                $arr_goods["mborderid"] = trim($this->input->post("mborder"));
            }
            if(trim($this->input->post("fmorder"))){
                $arr_goods["fmorderid"] = trim($this->input->post("fmorder"));
            }
            if(trim($this->input->post("property"))){
                $arr_goods["property"] = trim($this->input->post("property"));
            }
            if(trim($this->input->post("descr"))){
                $arr_goods["descr"] = trim($this->input->post("descr"));
            }
            //$arr_goods["createoper"] = $_COOKIE['userid']; //修改的时候不需要
            $arr_goods['oper'] = $_COOKIE['userid']; //修改人，修改时间
            $arr_goods['opertime'] = date("Y-m-d H:i:s");

            $id = trim($this->input->post('id'));
            $this->db->update("d_outproduct",$arr_goods,"id = '".$id."'");
            if($this->db->affected_rows()){
                $arr = array('code'=>200,"msg"=>"修改退货商品成功!");
            }else{
                $arr = array('code'=>0,"msg"=>"修改退货商品失败!");
            }
            echo json_encode($arr);exit;

        }else{
            $id = $this->input->get('id');
            $goodslist = $this->db->query("SELECT * FROM d_outproduct WHERE id = '".$id."'")->row_array();
            $this->tpl->assign('goodslist',$goodslist);
            $sql = "SELECT * FROM d_producttype ";    //获取商品型号
            $lists= $this->db->query($sql)->result_array();
            $this->tpl->assign('lists',$lists);
            $this->tpl->display("stocks/editreturngoods.tpl");
        }
    }
    public function manageGoods(){
        $id = trim($this->input->post('id'));
        $flag = trim($this->input->post('flag'));
        if(!$id){
            $arr = array('code'=>1,"msg"=>"参数错误");
            echo json_encode($arr);
            exit;
        }
        $this->db->trans_begin();	//事务开始
        //更新商品状态
       $this->db->update('d_outproduct',array('flag'=>$flag),"id = '".$id."'");
        //正常入库
        if($flag==2){
            $sql = "SELECT * FROM d_outproduct WHERE id = '".$id."'";
            $rs  = $this->db->query($sql)->row_array();
            if($rs){
                $arr_savenum = array();
                $date = $rs['opertime'];

                //查询相关记录
                $sql_type = "SELECT * FROM d_producttype WHERE id = '".$rs['producttype']."'";
                $rs_type  = $this->db->query($sql_type)->row_array();

                $arr_stocks = array();
                $arr_stocks['productsku'] = $rs['sku'];
                $arr_stocks['productname'] = $rs['skuname'];
                $arr_stocks['producttypename']=$rs_type['measure'].",".$rs_type['type'].",".$rs_type['age'];

                //当前库存表 跟批量订单保持一致，使用 producttypename查询 因批量订单未使用producttypeid
                $sql_savenum = "SELECT * FROM d_savenum WHERE productsku = '{$rs['sku']}' AND producttypename = '{$arr_stocks['producttypename']}' ORDER BY id DESC  ";
               // $sql_savenum = "SELECT * FROM d_savenum WHERE productsku = '{$rs['sku']}' AND producttypeid = '{$rs['producttype']}' ORDER BY id DESC  ";
                $rs_savenum  = $this->db->query($sql_savenum)->row_array();
                //如果存在则更新，否则插入
                if($rs_savenum&&$rs['producttype']){
                    //更新库存表
                    $arr_savenum['updatetime'] = $date;
                    $arr_savenum['updateoper'] = $_COOKIE['userid'];
                    $arr_savenum['savenum'] = $rs['ordernum']+$rs_savenum['savenum'];
                    $this->db->update('d_savenum',$arr_savenum,"id = '".$rs_savenum['id']."'");
                    //插入入库记录表
                    $arr_addsavenum = $arr_stocks;
                    $arr_addsavenum['oldsavenum'] = $rs_savenum['savenum'];
                    $arr_addsavenum['insavenum']  = $rs['ordernum'];
                    $arr_addsavenum['newsavenum'] = $rs_savenum['savenum']+$rs['ordernum'];
                    $arr_addsavenum['descr']= "退货入库";
                    $arr_addsavenum['createtime'] = $date;
                    $arr_addsavenum['factory'] = $rs['factory'];
                    $arr_addsavenum['createoper']= $_COOKIE['userid'];
                    $arr_addsavenum['savenumid']= $rs_savenum['id']; //库存表id

                    //$arr_addsavenum['outfactory'] ="";
                    //$arr_addsavenum['designer'] ="";
                    //马帮订单，或复漫订单id，应该一会全部使用复漫订单id
                    if($rs['fmorderid']){
                        $arr_addsavenum['orderid'] = $rs['fmorderid'];
                    }
                    $this->db->insert('d_addsavenum',$arr_addsavenum);

                    //插入一条日志信息
                    $arr_savenumnlog = $arr_stocks;
                    $arr_savenumnlog['producttypeid'] = $rs['producttype'];
                    $arr_savenumnlog['oldsavenum'] = $rs_savenum['savenum'];
                    $arr_savenumnlog['newsavenum'] = $rs_savenum['savenum']+$rs['ordernum'];
                    $arr_savenumnlog['descr'] = "退货入库";
                    $arr_savenumnlog['updatetime'] = $date;
                    $arr_savenumnlog['updateoper'] = $_COOKIE['userid'];
                    $arr_savenumnlog['savenumid'] = $rs_savenum['id'];
                    $this->db->insert('d_savenumlog',$arr_savenumnlog);
                   // print_r($arr_savenumnlog);exit;

                }else{
                    //插入库存表
                    $arr_savenum = $arr_stocks;
                    $arr_savenum['producttypeid'] = $rs['producttype'];
                    $arr_savenum['updatetime'] = $date;
                    $arr_savenum['updateoper'] = $_COOKIE['userid'];
                    $arr_savenum['savenum'] = $rs['ordernum'];
                    $arr_savenum['factory'] = $rs['factory'];
                    $this->db->insert('d_savenum',$arr_savenum);
                    $savenumid = $this->db->insert_id();
                    //入库记录表
                    $arr_addsavenum = $arr_stocks;
                    $arr_addsavenum['insavenum'] = $rs['ordernum'];
                    $arr_addsavenum['oldsavenum']=0;
                    $arr_addsavenum['newsavenum'] = $rs['ordernum'];
                    $arr_addsavenum['descr']= "退货入库";
                    $arr_addsavenum['createtime'] = $date;
                    $arr_addsavenum['factory'] = $rs['factory'];
                    $arr_addsavenum['createoper']= $_COOKIE['userid'];
                    $arr_addsavenum['savenumid']= $savenumid; //库存表id

                    //$arr_addsavenum['outfactory'] ="";
                    //$arr_addsavenum['designer'] ="";
                    //马帮订单，或复漫订单id，应该一会全部使用复漫订单id
                    if($rs['fmorderid']){
                        $arr_addsavenum['orderid'] = $rs['fmorderid'];
                    }
                    $this->db->insert('d_addsavenum',$arr_addsavenum);
                    //入库日志表
                    $arr_savenumnlog = $arr_stocks;
                    $arr_savenumnlog['producttypeid'] = $rs['producttype'];
                    $arr_savenumnlog['oldsavenum'] = 0;
                    $arr_savenumnlog['newsavenum'] = $rs['ordernum'];
                    $arr_savenumnlog['descr'] = "退货入库";
                    $arr_savenumnlog['updatetime'] = $date;
                    $arr_savenumnlog['updateoper'] = $_COOKIE['userid'];
                    $arr_savenumnlog['savenumid'] = $savenumid;

                    $this->db->insert('d_savenumlog',$arr_savenumnlog);

                }
            }
        }
        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            $arr = array('code'=>0,"msg"=>"更新失败");
            echo json_encode($arr);exit;
        }
        else
        {
            $this->db->trans_commit();
            $arr = array('code'=>200,"msg"=>"更新成功");
            echo json_encode($arr);exit;
        }



    }
    //库存列表
    public function stockList(){
        $where = " ";
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        //商品编号
        $goods_sku =  trim($this->input->get('goods_sku'));
        if($goods_sku){
            $where.= " AND a.productsku = '{$goods_sku}' ";
            $this->tpl->assign("goods_sku", $goods_sku);
        }
        $goods_name =  trim($this->input->get('goods_name'));
        if($goods_name){
            $where.= " AND a.productname = '{$goods_name}' ";
            $this->tpl->assign("goods_name", $goods_name);
        }
        $where .= " GROUP BY a.productsku ";
        $orderby = " order by a.productsku ASC";
        $fields = " a.id,a.productsku,a.productname,a.producttypename,a.alertnum, ".
            " sum(a.savenum) as savenum ";
        $list = $this->fun->getalllist('d_savenum a', $where, $nowpage, $if_csv, $this->pageSize, $orderby,$fields,$join);
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("stocklist", $list["list"]);
        $this ->tpl->display("stocks/stocklist.tpl");
    }
    //出库查询
    public function outStockSearch(){
        $where = " ";
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        //商品编号
        $goods_sku =  trim($this->input->get('goods_sku'));
        if($goods_sku){
            $where.= " AND a.productsku = '{$goods_sku}' ";
            $this->tpl->assign("goods_sku", $goods_sku);
        }
        $order_sku =  trim($this->input->get('order_sku'));
        if($order_sku){
            $where.= " AND a.orderid = '{$order_sku}' ";
            $this->tpl->assign("order_sku", $order_sku);
        }
        //工厂
		
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$where.=" AND a.factory = 1";
		}
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$where.=" AND a.factory = 2";
		}

//        $factory_id = $this->input->get('search_factorys');
//        if($factory_id){
//            $this->tpl->assign("search_factorys", $factory_id);
//            $where .= " AND a.factory = '$factory_id' ";
//        }
            //日期
        $starttime = trim($this->input->get('starttime'));
        if($starttime){
            $this->tpl->assign("starttime", $starttime);
            $where .= " AND a.createtime >= '$starttime' ";
        }
        $endtime = trim($this->input->get('endtime'));
        if($endtime){
            $this->tpl->assign("endtime", $endtime);
            $where .= " AND a.createtime <= '$endtime 23:59:59' ";
        }
        //$where .= " GROUP BY a.productsku ";
        $orderby = " order by a.createtime DESC ";
        //$orderby = " order by a.productsku ASC";
        $fields = " a.id,a.orderid,a.outsaveattr,a.productsku,a.productname,a.producttypename,a.oldsavenum,a.outsavenum,a.newsavenum, ".
            " a.createoper,a.createtime,a.descr,b.name as createopername,a.savenumid,a.flag ";
        $join = " LEFT JOIN d_user b On a.createoper = b.id ";
        $list = $this->fun->getalllist('d_outsavenum a', $where, $nowpage, $if_csv, $this->pageSize, $orderby,$fields,$join);
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("stocklist", $list["list"]);
        //获取工厂列表
        $factorys = $this->fun->getdatabaseslist("db_factory");
        $this->tpl->assign("factorys",$factorys );
        $this ->tpl->display("stocks/outstocksearch.tpl");
    }
    //入库查询
    public function inStockSearch(){
        $where = " ";
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        //商品编号
        $goods_sku =  trim($this->input->get('goods_sku'));
        if($goods_sku){
            $where.= " AND a.productsku = '{$goods_sku}' ";
            $this->tpl->assign("goods_sku", $goods_sku);
        }
        $order_sku =  trim($this->input->get('order_sku'));
        if($order_sku){
            $where.= " AND a.orderid = '{$order_sku}' ";
            $this->tpl->assign("order_sku", $order_sku);
        }
        //工厂
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$where.=" AND a.factory = 1";
		}
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$where.=" AND a.factory = 2";
		}
		if($_COOKIE["department"] ==1)	//工厂2人员
		{
			$factory_id = $this->input->get('search_factorys');
			if($factory_id){
				$this->tpl->assign("search_factorys", $factory_id);
				$where .= " AND a.factory = '$factory_id' ";
			}
		}
        //日期
        $starttime = trim($this->input->get('starttime'));
        if($starttime){
            $this->tpl->assign("starttime", $starttime);
            $where .= " AND a.createtime >= '$starttime' ";
        }
        $endtime = trim($this->input->get('endtime'));
        if($endtime){
            $this->tpl->assign("endtime", $endtime);
            $where .= " AND a.createtime <= '$endtime 23:59:59' ";
        }
        $where .= " AND a.productsku is not NULL ";
       //$where .= " GROUP BY a.productsku ";
        $orderby = " order by a.createtime DESC ";
        //$orderby = " order by a.productsku ASC";
        $fields = " a.id,a.orderid,a.productsku,a.productname,a.producttypename,a.oldsavenum,a.insavenum,a.newsavenum, ".
            " a.createoper,a.createtime,a.descr,b.name as createopername,a.flag,a.savenumid ";
        $join = " LEFT JOIN d_user b On a.createoper = b.id ";
        $list = $this->fun->getalllist('d_addsavenum a', $where, $nowpage, $if_csv, $this->pageSize, $orderby,$fields,$join);
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("stocklist", $list["list"]);
        //获取工厂列表
        $factorys = $this->fun->getdatabaseslist("db_factory");
        $this->tpl->assign("factorys",$factorys );
        $this ->tpl->display("stocks/instocksearch.tpl");
    }
    public function ajaxbutton(){
        $op =$action= $this->input->get_post('op');
        switch($action){
			case "confirmNeed":
                $this->confirmNeed();
				break; 
			case "saveNeedStore":
                $this->saveNeedStore();
                break; 
			case "storeNeedDetail":
                $this->storeNeedDetail();
            break;
            case "delStroeNeed":
                $this->delStroeNeed();  
            break;
            case "updateStock":
                $this->updateStock();  
            break;
        }
        //搜索商品信息
        if($op=="searchGoodsSku"){
            $goods_sku = trim($this->input->post('goods_sku'));
            $sql = "SELECT goods_name FROM db_goods WHERE goods_sku = '$goods_sku'";
            $result = $this->db->query($sql)->row_array();
            if($result){
                $arr_data = array('code'=>200,'msg'=>$result['goods_name']);
                echo json_encode($arr_data);exit;
            }else{
                $arr_data = array('code'=>0,'msg'=>"该商品编号不存在");
                echo json_encode($arr_data);exit;
            }

        }
        if($op=='downloadExcel'){
;            //商品编号
            $this->db->from('d_savenum');
            $goods_sku =  trim($this->input->get('goods_sku'));
            if($goods_sku){
                //$where.= " AND a.productsku = '{$goods_sku}' ";
                $this->tpl->assign("goods_sku", $goods_sku);
                $this->db->where('productsku',$goods_sku);
            }
            $goods_name =  trim($this->input->get('goods_name'));
            if($goods_name){
                //$where.= " AND a.productname = '{$goods_name}' ";
                $this->tpl->assign("goods_name", $goods_name);
                $this->db->where('productname',$goods_name);
            }
            $this->db->where('savenum >',0);
            $lists = $this->db->get()->result_array();
            //导出excel表格
            header("Content-type:application/vnd.ms-excel");
            header("Content-Disposition:filename=stocks.xls");
            echo "<table><tr>";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "商品编号")."</td>" ."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "商品名称")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "产品类型")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "库存数")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "警戒数")."</td>"."\t\n";
            echo "</tr>";
            foreach($lists as $k=>$v){
                echo "<tr>";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['productsku'])."</td>"."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['productname'])."</td>"."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['producttypename'])."</td>"."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['savenum'])."</td>"."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['alertnum'])."</td>"."\t\n";
                echo "</tr>";
            }
            echo "</table>";
        }
        if($op=="doShowStockDetails"){
            $productsku = $this->input->get('productsku');
            $where = "";
            $nowpage = $_REQUEST["pageid"];
            if ($nowpage == "") $nowpage = 1;
            $where.=" AND a.productsku = '{$productsku}' ";
            $orderby = " order by a.productsku ASC";
            $fields = " a.id,a.productsku,a.productname,a.producttypename,a.alertnum,a.updateoper, ".
                " a.savenum ";
            $list = $this->fun->getalllist('d_savenum a', $where, $nowpage, $if_csv, $this->pageSize, $orderby,$fields,$join);
            $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
            $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
            $this->tpl->assign("total", $list["total"]);
            $this->tpl->assign("pageList", $pageList);
            $this->tpl->assign("stocklist", $list["list"]);
            $this ->tpl->display("stocks/stockdetails.tpl");
        }
        if($op=="doShowStockLog"){
            $where = "";
            $nowpage = $_REQUEST["pageid"];
            if ($nowpage == "") $nowpage = 1;
            $savenumlog = $this->input->get('savenumid');
            if($savenumlog){
                $where.= " AND a.savenumid = '{$savenumlog}' ";
                $this->tpl->assign("savenumid", $savenumlog);
            }
            $goods_name =  trim($this->input->get('goods_name'));
            if($goods_name){
                $where.= " AND a.productname = '{$goods_name}' ";
                $this->tpl->assign("goods_name", $goods_name);
            }
            $search_date = trim($this->input->get('starttime'));
            if($search_date){
                $this->tpl->assign("starttime", $search_date);
                $where.= " AND a.updatetime like '$search_date%'";
            }

            $where.=" AND a.savenumid = {$savenumlog} ";
            $orderby = " order by a.id DESC";
            $fields = " a.id,a.productsku,a.productname,a.producttypename,a.descr,a.updateoper,a.updatetime,a.oldsavenum,a.newsavenum, ".
                " a.savenumid,b.name as opername";
            $join = " LEFT JOIN d_user b ON a.updateoper = b.id ";
            $list = $this->fun->getalllist('d_savenumlog a', $where, $nowpage, $if_csv, $this->pageSize, $orderby,$fields,$join);
            $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
            $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
            $this->tpl->assign("total", $list["total"]);
            $this->tpl->assign("pageList", $pageList);
            $this->tpl->assign("stocklist", $list["list"]);
            $this ->tpl->display("stocks/stocklogs.tpl");
        }
        //出库
        if($op=="outStocks"){
            if($this->input->post()){
                $outstock_num = trim($this->input->post('outstock_num'),",");
                $search_status= trim($this->input->post('search_status'),",");
                $outstock_order=trim($this->input->post('outstock_order'),",");
                $savenum_id=trim($this->input->post('savenum_id'),",");
                $arr_outstock_num = explode(",",$outstock_num); //出库数量
                $arr_search_status= explode(",",$search_status); //类型
                $arr_outstock_order= explode(",",$outstock_order);//出库订单
                $arr_savenum_id= explode(",",$savenum_id); //需要出库的库存id
                $goods_sku = $this->input->post('goods_sku');
                $descr = $this->input->post('descr');
                //更新相关数据库库存信息
                $this->db->trans_begin();
                $date = date("Y-m-d H:i:s");
                $userid = $_COOKIE['userid'];
                try{
                    foreach($arr_savenum_id as $k=>$v){ //$v为具体值
                        $sql = "SELECT a.id,a.productname,a.producttypename,a.productid,a.savenum,a.factory FROM d_savenum a WHERE a.id = $v AND a.savenum >= $arr_outstock_num[$k] FOR UPDATE ";
                        $rs = $this->db->query($sql)->row_array();
                        //更新库存
                        $num = $arr_outstock_num[$k];
                        $sql_upd = "UPDATE d_savenum SET updatetime= '{$date}',updateoper = {$userid},savenum = savenum - $num WHERE id = $v AND savenum >=0 ";
                        $upd_rs = $this->db->query($sql_upd);
                        if($this->db->affected_rows()){
                            //插入出库记录
                            $arr_outstock['productsku'] = $goods_sku; //商品编号
                            $arr_outstock['orderid'] = $arr_outstock_order[$k]; //订单号
                            $arr_outstock['descr'] = $descr; //描述
                            $arr_outstock['createtime']=$date;
                            $arr_outstock['createoper']=$userid;
                            $arr_outstock['savenumid']=$v; //id号
                            $arr_outstock['outsaveattr']=$arr_search_status[$k];
                            $arr_outstock['producttypename']=$rs['producttypename'];
                            $arr_outstock['productid']=$rs['productid'];
                            $arr_outstock['oldsavenum']=$rs['savenum']; //出库前数量
                            $arr_outstock['outsavenum']=$arr_outstock_num[$k];//出库数量
                            $arr_outstock['newsavenum']=$rs['savenum']-$arr_outstock_num[$k]; //出库后数量
                            $arr_outstock['productname']=$rs['productname'];//商品名称
                            $arr_outstock['factory']=$rs['factory'];//工厂id
                            $this->db->insert('d_outsavenum',$arr_outstock);
                            //插入库存日志数据
                            $arr_log['productid']=$rs['productid'];
                            $arr_log['productsku'] = $goods_sku; //商品编号
                            $arr_log['productname']=$rs['productname'];//商品名称
                            $arr_log['producttypename']=$rs['producttypename'];
                            $arr_log['oldsavenum']=$rs['savenum']; //出库前数量
                            $arr_log['newsavenum']=$rs['savenum']-$arr_outstock_num[$k]; //出库后数量
                            $arr_log['descr'] = $descr; //描述
                            $arr_log['updatetime']=$date;
                            $arr_log['updateoper']=$userid;
                            $arr_log['savenumid']=$v; //id号
                            $this->db->insert('d_savenumlog',$arr_log);
                        }else{
                            $this->db->trans_rollback();
                            $count = $k+1;
                            $arr_back = array('code'=>0,'msg'=>"第".$count."个库存数不足!");
                            echo json_encode($arr_back);exit;
                        }

                    }
                    $this->db->trans_commit();
                    $arr_back = array('code'=>1,'msg'=>"成功");
                    echo json_encode($arr_back);exit;
                }catch (Exception $e){
                    $arr_back = array('code'=>0,'msg'=>$e->getMessage());
                    $this->db->trans_rollback();
                    echo json_encode($arr_back);exit;
                }

            }else{
                //$num = $this->input->get('num'); //出库标记
                $str_param = trim($this->input->get('s'),",");
                $arr_id = explode(",",$str_param); //为获取的id号
                $arr_savenum = array();
                foreach($arr_id as $k=>$v){
                    $sql = "SELECT * FROM d_savenum WHERE id = $v ";
                    $rs  = $this->db->query($sql)->row_array();
                    $arr_savenum[$k] = $rs;
                }
                $this->tpl->assign('goods_sku',$arr_savenum[0]['productsku']);
                $this->tpl->assign("stocklist",$arr_savenum);
                $this ->tpl->display("stocks/addoutstock.tpl");

            }
        }
        //退货
        if($op=="returnGoods"){
            if($this->input->post()){
                $outstock_num = trim($this->input->post('outstock_num'),",");
                $outstock_order=trim($this->input->post('outstock_order'),",");
                $savenum_id=trim($this->input->post('savenum_id'),",");
                $arr_outstock_num = explode(",",$outstock_num); //出库数量
                $arr_outstock_order= explode(",",$outstock_order);//出库订单
                $arr_savenum_id= explode(",",$savenum_id); //需要出库的库存id
                $goods_sku = $this->input->post('goods_sku');
                $descr = $this->input->post('descr');
                //更新相关数据库库存信息
                $this->db->trans_begin();
                $date = date("Y-m-d H:i:s");
                $userid = $_COOKIE['userid'];
                try{
                    foreach($arr_savenum_id as $k=>$v){ //$v为具体值
                        $sql = "SELECT a.id,a.productname,a.producttypename,a.productid,a.savenum,a.factory FROM d_savenum a WHERE a.id = $v AND a.savenum >= $arr_outstock_num[$k] FOR UPDATE ";
                        $rs = $this->db->query($sql)->row_array();
                        //更新库存
                        $num = $arr_outstock_num[$k];
                        $sql_upd = "UPDATE d_savenum SET updatetime= '{$date}',updateoper = {$userid},savenum = savenum + $num WHERE id = $v AND savenum >=0 ";
                        $upd_rs = $this->db->query($sql_upd);
                        if($this->db->affected_rows()){
                            //入库数增加
                            $arr_outstock['productid']=$rs['productid'];
                            $arr_outstock['productsku'] = $goods_sku; //商品编号
                            $arr_outstock['insavenum']=$arr_outstock_num[$k];//入库数量
                            $arr_outstock['oldsavenum']=$rs['savenum']; //入库前数量
                            $arr_outstock['newsavenum']=$rs['savenum']+$arr_outstock_num[$k]; //入库后数量
                            $arr_outstock['descr'] = $descr; //描述
                            $arr_outstock['createtime']=$date;
                            $arr_outstock['createoper']=$userid;
                            $arr_outstock['productname']=$rs['productname'];//商品名称
                            $arr_outstock['factory']=$rs['factory'];//工厂id
                            $arr_outstock['savenumid']=$v; //id号
                            $arr_outstock['producttypename']=$rs['producttypename'];
                            $arr_outstock['orderid'] = $arr_outstock_order[$k]; //订单号
                            $this->db->insert('d_addsavenum',$arr_outstock);
                            //插入库存日志数据
                            $arr_log['productid']=$rs['productid'];
                            $arr_log['productsku'] = $goods_sku; //商品编号
                            $arr_log['productname']=$rs['productname'];//商品名称
                            $arr_log['producttypename']=$rs['producttypename'];
                            $arr_log['oldsavenum']=$rs['savenum']; //退货前数量
                            $arr_log['newsavenum']=$rs['savenum']+$arr_outstock_num[$k]; //退货后数量
                            $arr_log['descr'] = $descr; //描述
                            $arr_log['updatetime']=$date;
                            $arr_log['updateoper']=$userid;
                            $arr_log['savenumid']=$v; //id号
                            $this->db->insert('d_savenumlog',$arr_log);
                        }else{
                            $this->db->trans_rollback();
                            $count = $k+1;
                            $arr_back = array('code'=>0,'msg'=>"第".$count."个参数错误!");
                            echo json_encode($arr_back);exit;
                        }

                    }
                    $this->db->trans_commit();
                    $arr_back = array('code'=>1,'msg'=>"成功");
                    echo json_encode($arr_back);exit;
                }catch (Exception $e){
                    $arr_back = array('code'=>0,'msg'=>$e->getMessage());
                    $this->db->trans_rollback();
                    echo json_encode($arr_back);exit;
                }

            }else{
                //$num = $this->input->get('num'); //退货标记
                $str_param = trim($this->input->get('s'),",");
                $arr_id = explode(",",$str_param); //为获取的id号
                $arr_savenum = array();
                foreach($arr_id as $k=>$v){
                    $sql = "SELECT * FROM d_savenum WHERE id = $v ";
                    $rs  = $this->db->query($sql)->row_array();
                    $arr_savenum[$k] = $rs;
                }
                $this->tpl->assign('goods_sku',$arr_savenum[0]['productsku']);
                $this->tpl->assign("stocklist",$arr_savenum);
                $this ->tpl->display("stocks/returngoods.tpl");

            }

        }
        //盘点
        if($op=="checkGoods"){
            if($this->input->post()){
                $outstock_num = trim($this->input->post('outstock_num'),",");
                $outstock_order=trim($this->input->post('outstock_order'),",");
                $savenum_id=trim($this->input->post('savenum_id'),",");
                $arr_outstock_num = explode(",",$outstock_num); //出库数量
                $arr_outstock_order= explode(",",$outstock_order);//出库订单
                $arr_savenum_id= explode(",",$savenum_id); //需要出库的库存id
                $goods_sku = $this->input->post('goods_sku');
                $descr = $this->input->post('descr');
                //更新相关数据库库存信息
                $this->db->trans_begin();
                $date = date("Y-m-d H:i:s");
                $userid = $_COOKIE['userid'];
                try{
                    foreach($arr_savenum_id as $k=>$v){ //$v为具体值
                        $sql = "SELECT a.id,a.productname,a.producttypename,a.productid,a.savenum,a.factory FROM d_savenum a WHERE a.id = $v AND a.savenum >= $arr_outstock_num[$k] FOR UPDATE ";
                        $rs = $this->db->query($sql)->row_array();
                        //更新库存
                        $num = $arr_outstock_num[$k];
                        $sql_upd = "UPDATE d_savenum SET updatetime= '{$date}',updateoper = {$userid},savenum =$num WHERE id = $v ";
                        $upd_rs = $this->db->query($sql_upd);
                        if($this->db->affected_rows()){
                            //插入库存日志数据
                            $arr_log['productid']=$rs['productid'];
                            $arr_log['productsku'] = $goods_sku; //商品编号
                            $arr_log['productname']=$rs['productname'];//商品名称
                            $arr_log['producttypename']=$rs['producttypename'];
                            $arr_log['oldsavenum']=$rs['savenum']; //盘点前数量
                            $arr_log['newsavenum']=$arr_outstock_num[$k]; //盘点后后数量
                            $arr_log['descr'] = "盘点"; //描述
                            $arr_log['updatetime']=$date;
                            $arr_log['updateoper']=$userid;
                            $arr_log['savenumid']=$v; //id号
                            $this->db->insert('d_savenumlog',$arr_log);
                        }else{
                            $this->db->trans_rollback();
                            $count = $k+1;
                            $arr_back = array('code'=>0,'msg'=>"第".$count."个参数错误!");
                            echo json_encode($arr_back);exit;
                        }

                    }
                    $this->db->trans_commit();
                    $arr_back = array('code'=>1,'msg'=>"成功");
                    echo json_encode($arr_back);exit;
                }catch (Exception $e){
                    $arr_back = array('code'=>0,'msg'=>$e->getMessage());
                    $this->db->trans_rollback();
                    echo json_encode($arr_back);exit;
                }

            }else{
                //$num = $this->input->get('num'); //盘点标记
                $str_param = trim($this->input->get('s'),",");
                $arr_id = explode(",",$str_param); //为获取的id号
                $arr_savenum = array();
                foreach($arr_id as $k=>$v){
                    $sql = "SELECT * FROM d_savenum WHERE id = $v ";
                    $rs  = $this->db->query($sql)->row_array();
                    $arr_savenum[$k] = $rs;
                }
                $this->tpl->assign('goods_sku',$arr_savenum[0]['productsku']);
                $this->tpl->assign("stocklist",$arr_savenum);
                $this ->tpl->display("stocks/checkgoods.tpl");

            }

        }
        //标签 实际为打印
        if($op=="printGoods"){
            $flag = $this->input->get('flag');
            if($flag){
                //显示选中的打印界面
            }else{
                $str_param = trim($this->input->get('s'),",");
                $arr_id = explode(",",$str_param); //为获取的id号
                $arr_savenum = array();
                foreach($arr_id as $k=>$v){
                    $sql = "SELECT * FROM d_savenum WHERE id = $v ";
                    $rs  = $this->db->query($sql)->row_array();
                    //$arr_savenum[$k] = $rs;
                    $arr_size = explode(',',$rs['producttypename']);
                    $productsku = $rs['productsku']."  ".$arr_size[0];
                    $arr_savenum[$k]['productsku'] = $productsku;
                    $arr_savenum[$k]['productname'] = $rs['productname'];
                    $arr_savenum[$k]['updatetime'] = date("Y-m-d",strtotime($rs['updatetime']))." ".$rs['producttypename'];


                }
                $this->tpl->assign("stocklist",$arr_savenum);
                $this ->tpl->display("stocks/printgoods.tpl",0,0,1);
            }

        }
        //出库总览
        if($op=="outStockInfos"){
            $where = " WHERE 1 ";
            $flag = 0;
            //工厂
            $factory_id = $this->input->get('search_factorys');
            if($factory_id){
                $where .= " AND a.factory = '$factory_id' ";
                $this->tpl->assign("search_factorys", $factory_id);
                $flag = $flag +1;
            }
            //日期
            $starttime = trim($this->input->get('starttime'));
            if(!empty($starttime)){
                $where .= " AND a.createtime like '$starttime %' ";
                $this->tpl->assign("starttime", $starttime);
                $flag = $flag +1;
            }
            //获取工厂列表
            $factorys = $this->fun->getdatabaseslist("db_factory");
            $this->tpl->assign("factorys",$factorys );
            if($flag){
                //根据条件进行检索
                $where .= " GROUP BY a.factory ";
                $fields = " sum(a.outsavenum) as outsavenum,a.createtime,c.name as factoryname ";
                $join.= " LEFT JOIN db_factory c ON a.factory = c.id ";
                $sql = "SELECT $fields FROM d_outsavenum a ".$join.$where;
                $lists = $this->db->query($sql)->result_array();
                $this->tpl->assign("stocklist",$lists);
            }
            $this ->tpl->display("stocks/outstockinfos.tpl");
        }
        //出库查询 撤销
        if($op=="doOutStockRevoke"){
            $id = $this->input->post('id'); //出库id
            $savenumid = $this->input->post('savenumid'); //库存id
            //更新相关数据库库存信息
            $this->db->trans_begin();
            $date = date("Y-m-d H:i:s");
            $userid = $_COOKIE['userid'];
            try{
                    $sql_out = "SELECT * FROM d_outsavenum WHERE id = $id ";
                    $res = $this->db->query($sql_out)->row_array();
                    if($res){
                        //将原有的记录flag也更新
                        $this->db->where('id',$id);
                        $arr_out['flag'] = 1;
                        $this->db->update('d_outsavenum',$arr_out);
                        //插入出库记录
                        $arr_outstock['productsku'] = $res['productsku']; //商品编号
                        $arr_outstock['orderid'] = $res['orderid']; //订单号
                        $arr_outstock['descr'] = "撤销"; //描述
                        $arr_outstock['createtime']=$date;
                        $arr_outstock['createoper']=$userid;
                        $arr_outstock['savenumid']=$savenumid; //id号
                        $arr_outstock['outsaveattr']=$res['outsaveattr'];
                        $arr_outstock['producttypename']=$res['producttypename'];
                        $arr_outstock['productid']=$res['productid'];
                        $arr_outstock['oldsavenum']=$res['newsavenum']; //出库前数量
                        $arr_outstock['outsavenum']=-$res['outsavenum'];//出库数量
                        $arr_outstock['newsavenum']=$res['savenum']+$res['outsavenum']; //出库后数量
                        $arr_outstock['productname']=$res['productname'];//商品名称
                        $arr_outstock['factory']=$res['factory'];//工厂id
                        $arr_outstock['flag']= 1;
                        $this->db->insert('d_outsavenum',$arr_outstock);
                        //对库存表进行更新
                        $sql = "SELECT a.id,a.productname,a.producttypename,a.productid,a.savenum,a.factory FROM d_savenum a WHERE a.id = $savenumid  ";
                        $rs = $this->db->query($sql)->row_array();
                        //更新库存
                        $sql_upd = "UPDATE d_savenum SET updatetime= '{$date}',updateoper = {$userid},savenum = savenum+{$res['outsavenum']} WHERE id = $savenumid ";
                        $upd_rs = $this->db->query($sql_upd);
                            //插入库存日志数据
                            $arr_log['productid']=$rs['productid'];
                            $arr_log['productsku'] = $goods_sku; //商品编号
                            $arr_log['productname']=$rs['productname'];//商品名称
                            $arr_log['producttypename']=$rs['producttypename'];
                            $arr_log['oldsavenum']=$rs['savenum']; //盘点前数量
                            $arr_log['newsavenum']=$rs['savenum']-$res['outsavenum']; //盘点后后数量
                            $arr_log['descr'] = "撤销"; //描述
                            $arr_log['updatetime']=$date;
                            $arr_log['updateoper']=$userid;
                            $arr_log['savenumid']=$savenumid; //id号
                            $this->db->insert('d_savenumlog',$arr_log);

                    }else{
                        $arr_back = array('code'=>0,'msg'=>"该出库记录不存在！");
                        echo json_encode($arr_back);exit;
                    }
                $this->db->trans_commit();
                $arr_back = array('code'=>1,'msg'=>"成功");
                echo json_encode($arr_back);exit;
            }catch (Exception $e){
                $arr_back = array('code'=>0,'msg'=>$e->getMessage());
                $this->db->trans_rollback();
                echo json_encode($arr_back);exit;
            }

        }
        //入库查询 撤销
        if($op=="doInStockRevoke"){
            $id = $this->input->post('id'); //出库id
            $savenumid = $this->input->post('savenumid'); //库存id
            //更新相关数据库库存信息
            $this->db->trans_begin();
            $date = date("Y-m-d H:i:s");
            $userid = $_COOKIE['userid'];
            try{
                $sql_out = "SELECT * FROM d_addsavenum WHERE id = $id ";
                $res = $this->db->query($sql_out)->row_array();
                if($res){
                    //将原有的记录flag也更新
                    $this->db->where('id',$id);
                    $arr_out['flag'] = 1;
                    $this->db->update('d_addsavenum',$arr_out);
                    //插入入库记录
                    $arr_outstock['productsku'] = $res['productsku']; //商品编号
                    $arr_outstock['orderid'] = $res['orderid']; //订单号
                    $arr_outstock['descr'] = "撤销"; //描述
                    $arr_outstock['createtime']=$date;
                    $arr_outstock['createoper']=$userid;
                    $arr_outstock['savenumid']=$savenumid; //id号
                    //$arr_outstock['outsaveattr']=$res['outsaveattr'];
                    $arr_outstock['producttypename']=$res['producttypename'];
                    $arr_outstock['productid']=$res['productid'];
                    $arr_outstock['oldsavenum']=$res['newsavenum']; //出库前数量
                    $arr_outstock['insavenum'] = -$res['insavenum'];//出库数量
                    $arr_outstock['newsavenum']=$res['newsavenum']-$res['insavenum']; //出库后数量
                    $arr_outstock['productname']=$res['productname'];//商品名称
                    $arr_outstock['factory']=$res['factory'];//工厂id
                    $arr_outstock['flag']= 1;
                    $this->db->insert('d_addsavenum',$arr_outstock);
                    //对库存表进行更新
                    $sql = "SELECT a.id,a.productname,a.producttypename,a.productid,a.savenum,a.factory FROM d_savenum a WHERE a.id = $savenumid  ";
                    $rs = $this->db->query($sql)->row_array();
                    //更新库存
                    $sql_upd = "UPDATE d_savenum SET updatetime= '{$date}',updateoper = {$userid},savenum = savenum-{$res['insavenum']} WHERE id = $savenumid ";
                    $upd_rs = $this->db->query($sql_upd);
                    //插入库存日志数据
                    $arr_log['productid']=$rs['productid'];
                    $arr_log['productsku'] = $goods_sku; //商品编号
                    $arr_log['productname']=$rs['productname'];//商品名称
                    $arr_log['producttypename']=$rs['producttypename'];
                    $arr_log['oldsavenum']=$rs['savenum']; //盘点前数量
                    $arr_log['newsavenum']=$rs['savenum']-$res['outsavenum']; //盘点后后数量
                    $arr_log['descr'] = "撤销"; //描述
                    $arr_log['updatetime']=$date;
                    $arr_log['updateoper']=$userid;
                    $arr_log['savenumid']=$savenumid; //id号
                    $this->db->insert('d_savenumlog',$arr_log);

                }else{
                    $arr_back = array('code'=>0,'msg'=>"该入库记录不存在！");
                    echo json_encode($arr_back);exit;
                }
                $this->db->trans_commit();
                $arr_back = array('code'=>1,'msg'=>"成功");
                echo json_encode($arr_back);exit;
            }catch (Exception $e){
                $arr_back = array('code'=>0,'msg'=>$e->getMessage());
                $this->db->trans_rollback();
                echo json_encode($arr_back);exit;
            }

        }
        //出库查询下载excel
        if($op=="downloadOutStockExcel"){
            $where = " where 1 ";
            //商品编号
            $goods_sku =  trim($this->input->get('goods_sku'));
            if($goods_sku){
                $where.= " AND a.productsku = '{$goods_sku}' ";
            }
            $order_sku =  trim($this->input->get('order_sku'));
            if($order_sku){
                $where.= " AND a.orderid = '{$order_sku}' ";
            }
            //工厂
            $factory_id = $this->input->get('search_factorys');
            if($factory_id){
                $where .= " AND a.factory = '$factory_id' ";
            }
            //日期
            $starttime = trim($this->input->get('starttime'));
            if(!empty($starttime)){
                $where .= " AND a.createtime >= '$starttime' ";
            }
            $endtime = trim($this->input->get('endtime'));
            if(!empty($endtime)){
                $where .= " AND a.createtime <= '$endtime 23:59:59' ";
            }
            $where .= " GROUP BY a.productsku ";
            $orderby = " order by a.productsku ASC";
            $fields = " a.id,a.orderid,a.outsaveattr,a.productsku,a.productname,a.producttypename,a.oldsavenum,a.outsavenum,a.newsavenum, ".
                " a.createoper,a.createtime,a.descr,b.name as createopername ";
            $join = " LEFT JOIN d_user b On a.createoper = b.id ";
            $sql = "SELECT $fields FROM d_outsavenum a ".$join.$where.$orderby;
            $lists = $this->db->query($sql)->result_array();
            //导出excel表格
            header("Content-type:application/vnd.ms-excel");
            header("Content-Disposition:filename=outstocks.xls");
            echo "<table><tr>";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "订单编号(对应复漫)")."</td>" ."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "关联")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "商品编号")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "商品名称")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "型号")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "出库前数量")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "出库数量")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "出库后数量")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "出库时间")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "出库人")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "描述")."</td>"."\t\n";
            echo "</tr>";
            foreach($lists as $k=>$v){
                echo "<tr>";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['orderid'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['outsaveattr'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['productsku'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['productname'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['producttypename'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['oldsavenum'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['outsavenum'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['newsavenum'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['createtime'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['createopername'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['descr'])."</td>" ."\t\n";
                echo "</tr>";
            }
            echo "</table>";
        }
        //入库查询下载excel
        if($op=="downloadInStockExcel"){
            $where = " where 1 ";
            //商品编号
            $goods_sku =  trim($this->input->get('goods_sku'));
            if($goods_sku){
                $where.= " AND a.productsku = '{$goods_sku}' ";
            }
            $order_sku =  trim($this->input->get('order_sku'));
            if($order_sku){
                $where.= " AND a.orderid = '{$order_sku}' ";
            }
            //工厂
            $factory_id = $this->input->get('search_factorys');
            if($factory_id){
                $where .= " AND a.factory = '$factory_id' ";
            }
            //日期
            $starttime = trim($this->input->get('starttime'));
            if(!empty($starttime)){
                $where .= " AND a.createtime >= '$starttime' ";
            }
            $endtime = trim($this->input->get('endtime'));
            if(!empty($endtime)){
                $where .= " AND a.createtime <= '$endtime 23:59:59' ";
            }
            $where .= " GROUP BY a.productsku ";
            $orderby = " order by a.productsku ASC";
            $fields = " a.id,a.orderid,a.productsku,a.productname,a.producttypename,a.oldsavenum,a.insavenum,a.newsavenum, ".
                " a.createoper,a.createtime,a.descr,b.name as createopername ";
            $join = " LEFT JOIN d_user b On a.createoper = b.id ";
            $sql = "SELECT $fields FROM d_addsavenum a ".$join.$where.$orderby;
            $lists = $this->db->query($sql)->result_array();
            //导出excel表格
            header("Content-type:application/vnd.ms-excel");
            header("Content-Disposition:filename=instocks.xls");
            echo "<table><tr>";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "订单编号(对应复漫)")."</td>" ."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "商品编号")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "商品名称")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "型号")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "出库前数量")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "出库数量")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "出库后数量")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "出库时间")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "出库人")."</td>"."\t";
            echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", "描述")."</td>"."\t\n";
            echo "</tr>";
            foreach($lists as $k=>$v){
                echo "<tr>";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['orderid'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['productsku'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['productname'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['producttypename'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['oldsavenum'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['insavenum'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['newsavenum'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['createtime'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['createopername'])."</td>" ."\t";
                echo "<td style='border:1px solid; width: 200px;text-align: center;'>".iconv("UTF-8", "GB2312//IGNORE", $v['descr'])."</td>" ."\t\n";
                echo "</tr>";
            }
            echo "</table>";
        }
    }
    
}